<template>
  <div class="app-container">
    <div class="filter-container">
      <p style="float:left;margin-top:5px;margin-left:2%">app当前版本：</p>
      <el-input v-model="listQuery.appCurrentVersion" size="small" placeholder="请输入app当前版本" style="width: 150px;float:left"
        class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button size="small" class="filter-item" type="success" icon="el-icon-search" style="margin-left:3%" @click="handleFilter">
        搜索
      </el-button>
      <el-button size="small" class="filter-item" style="margin-left: 10px;float:right" type="primary" icon="el-icon-edit"
        @click="handleCreate">添加</el-button>
    </div>

    <el-table v-loading="listLoading" :key="tableKey" :data="list" size="small" border fit highlight-current-row style="width: 100%;margin-top:1%"
      @selection-change="handleSelectionChange">
      <el-table-column label="ID" width="50px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="APP当前版本" width="100px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.appCurrentVersion }}</span>
        </template>
      </el-table-column>
      <el-table-column label="版本号" width="100px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.versionStr }}</span>
        </template>
      </el-table-column>
      <el-table-column label="渠道" width="100px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.sign=='B'?'B端APP':scope.row.sign=='C'?'C端APP':'' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="新增功能简介" min-width="250px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.addContent }}</span>
        </template>
      </el-table-column>
      <el-table-column label="下载地址" min-width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.appDownUrl }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否强制更新" width="100px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.isForceUpdate==1?'是':'否' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="添加时间" width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.updateTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="250px" class-name="small-padding fixed-width">
        <template slot-scope="{ row }">

          <el-button size="small" align="center" type="primary" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="small" align="center" type="danger" @click="handledelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize"
      @pagination="getList" />

    <el-dialog :close-on-click-modal="false" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible"
      append-to-body>
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="150px" style="width: 400px; margin-left:50px;">

        <el-form-item label="当前版本：" prop="appCurrentVersion">
          <el-input v-model="temp.appCurrentVersion" />
        </el-form-item>
        <el-form-item label="新增功能：" prop="addContent">
          <el-input v-model="temp.addContent" />
        </el-form-item>
        <el-form-item label="版本号：" prop="versionStr">
          <el-input v-model="temp.versionStr" />
        </el-form-item>
        <el-form-item label="渠道：" prop="sign">
         <el-select v-model="temp.sign" size="small" placeholder="全部" class="filter-item" style="width: 130px">
           <el-option v-for="item in qudaoTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
           </el-select>
        </el-form-item>

        <el-form-item label="上传apk：">
          <el-upload class="upload-demo" action="#" v-loading="dialogLoading" :show-file-list="false"
            :http-request="addImg">
            <el-button size="small" type="primary">点击上传</el-button>
            <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
          </el-upload>
        </el-form-item>

        <el-form-item label="下载地址：" prop="appDownUrl">
          <el-input v-model="temp.appDownUrl" />
        </el-form-item>

        <el-form-item label="是否强制更新：" prop="isForceUpdate">
         <el-select v-model="temp.isForceUpdate" size="small" placeholder="全部" class="filter-item" style="width: 130px">
           <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
           </el-select>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          返回
        </el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    updateManu,
    manufacturerList,
    delManufacturer,
    createManufacturer,
    batchDel
  } from '@/api/manufacturer' // 异步请求 delLly

  import {
    getListPage,
    addAppVersion,
    updateAppVersion,
    deleteAppVersion
  } from '@/api/appVersionReq'
  import {
    deleteFile,
    uploadFile
  } from '@/api/publicReq'
  import {
    parseTime
  } from '@/utils'
  import Pagination from '@/components/Pagination' // 分页插件

  const calendarTypeOptions = [{
      key: '0',
      display_name: '否'
    },
    {
      key: '1',
      display_name: '是'
    }
  ]
  const qudaoTypeOptions = [
  { key: 'B', display_name: 'B端APP' },
  { key: 'C', display_name: 'C端APP' },
]
const calendarqudaoKeyValue = qudaoTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})
  const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name
    return acc
  }, {})

  export default {
    inject:["reload"],
    components: {
      Pagination
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: 'success',
          draft: 'info',
          deleted: 'danger'
        }
        return statusMap[status]
      },
      typeFilter(type) {
        return calendarTypeKeyValue[type]
      }
    },
    data() {
      return {
        dateValue: [],
        tableKey: 0,
        list: null,
        uploadData: '',
        dialogLoading:false,
        total: 0,
        listLoading: true,
        listQuery: {
          pageNum: 1,
          pageSize: 10,
          appCurrentVersion: '',
          sort: '+id'
        },
        formImgUrl: "",
        deps: [],
        qudaoTypeOptions,
        calendarTypeOptions,
        sortOptions: [{
          label: 'ID Ascending',
          key: '+id'
        }, {
          label: 'ID Descending',
          key: '-id'
        }],
        statusOptions: ['published', 'draft', 'deleted'],
        showReviewer: false,
        temp: {
          id: undefined,
        },
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '修改',
          create: '添加'
        },
        rowId: "",
        dialogPvVisible: false,
        outerVisible: false,
        pvData: [],
        rules: {
          appCurrentVersion: [{
            required: true,
            message: '请输入当前版本',
            trigger: 'blur'
          }],
          addContent: [{
            type: 'date',
            required: true,
            message: '请输入新增功能',
            trigger: 'blur'
          }],
          versionStr: [{
            required: true,
            message: '请输入版本号',
            trigger: 'blur'
          }],
          sign: [{
            required: true,
            message: '请选择渠道',
            trigger: 'change'
          }],
          appDownUrl: [{
            required: true,
            message: '请上传下载地址',
            trigger: 'blur'
          }],
          isForceUpdate: [{
            required: true,
            message: '请选择是否强制更新',
            trigger: 'change'
          }],
        },
        downloadLoading: false,
        liaUser: null,
        ids: [],
        select: null
      }
    },
    created() {
      this.getList()
    },
    methods: {
      handleSelectionChange(val) {
        val.forEach((item) => {
          this.select = item.id
        })
        this.ids.push(this.select)
      },

      // 获取闪频广告的list
      getList() {
        this.listLoading = true
        var params = {
          // pageConvert: true,
          pageNum: this.listQuery.pageNum,
          pageSize: this.listQuery.pageSize,
          appCurrentVersion: this.listQuery.appCurrentVersion,
          // status: this.listQuery.status
        }
        getListPage(params).then(response => {
          this.list = response.data
          console.log(response)
          this.total = response.recordsTotal
          console.log(this.total)
          // Just to simulate the time of the request
          this.listLoading = false
        })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      handleModifyStatus(row, status) {
        this.$message({
          message: '操作Success',
          type: 'success'
        })
        row.status = status
      },
      sortChange(data) {
        const {
          prop,
          order
        } = data
        if (prop === 'id') {
          this.sortByID(order)
        }
      },
      sortByID(order) {
        if (order === 'ascending') {
          this.listQuery.sort = '+id'
        } else {
          this.listQuery.sort = '-id'
        }
        this.handleFilter()
      },
      resetTemp() {
        this.temp = {
          id: undefined
        }
      },
      // 编辑
      handleUpdate(row) {
        this.temp = Object.assign({}, row) // copy obj
        this.dateValue = [this.temp.broadStart, this.temp.broadEnd]
        this.formImgUrl = this.temp.broadPic
        // this.temp.timestamp = new Date(this.temp.timestamp)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      // 播放结束 handleEnd
      handleEnd(row) {
        this.$confirm('确定结束播放？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {

          var rowId = row.id
          timeoutScreenAds(rowId).then(res => {
            this.$message({
              type: 'success',
              message: '成功!'
            });
            this.getList()
          })
          // })

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });

      },
      updateData() {
        const tempData = Object.assign({}, this.temp)
        console.log(tempData)
        updateAppVersion(tempData).then(() => {
          for (const v of this.list) {
            if (v.id === this.temp.id) {
              const index = this.list.indexOf(v)
              this.list.splice(index, 1, this.temp)
              break
            }
          }
          this.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: '修改成功',
            type: 'success',
            duration: 2000
          })
          this.reload()
        })
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },

      // 上传apk
      addImg(data) {
        this.dialogLoading = true;
        const formData = new FormData();
        formData.append("file", data.file);
        console.log(data.file)
        uploadFile(formData).then(res => {
          console.log(res)
          this.dialogLoading = false;
          this.uploadData = res.data;
          this.temp.appDownUrl = res.data.filePath;
        });
      },

      // 添加数据
      createData() {
        console.log(this.temp)
        var formdata = this.temp

        addAppVersion(formdata).then(() => {
          this.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: '添加成功',
            type: 'success',
            duration: 2000
          })
          this.reload()
        })
      },


      handledelete(row) {
        // this.rowId=row.broadPic
        this.$confirm('确定删除？ 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
          console.log(row)
          deleteAppVersion(row.id).then(result => {
            console.log('result', result)
            var remove = row.appDownUrl
            String.prototype.replaceAll = function(s1, s2) {
              return this.replace(new RegExp(s1, "gm"), s2);
            }
            console.log(remove.replaceAll('/', '*'))
            var newRemove = remove.replaceAll('/', '*')
            var fordmata = {
              fileName: newRemove
            }
            deleteFile(newRemove).then(res => {
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.getList()
            })
          })

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });

      },
      getSortClass: function(key) {
        const sort = this.listQuery.sort
        return sort === `+${key}` ?
          'ascending' :
          sort === `-${key}` ?
          'descending' :
          ''
      },


    }
  }
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
